var express = require('express');
var router = express.Router();
var config = require('../config/db')
var MongoClient = require('mongodb').MongoClient
var bcrypt = require('bcryptjs')
var passport = require('passport')
var mongdb = require('mongodb')
/* 搜索图书 */
router.get('/getSearchBooksInfo', function (req, res, next) {
    //1.接受查询的数据（图书的名称） req.body
    var search = req.body
    //2.连接数据库MongoDB
    MongoClient.connect(config.url, function (err, client) {
        if (err) {
            console.log('数据库连接失败！', err)
            res.json({ code: 200, message: 'error', data: err })
        } else {
            //3.执行查询图书操作 db.find
            var db = client.db()
            db.collection('books').aggregate([
                { $match: { productName: `/^${search}/gi ` } } //查询的筛选条件
            ])
                .toArray(function (err, result) {
                    if (err) {
                        console.log('查询数据失败！', err)
                    } else {
                        //4.返回结果{code:0;message:'ok',data:{}}
                        res.json({ code: 200, message: 'ok', data: result })
                        client.close()
                    }
                })
        }
    })
});


/*获取所有图书*/
router.get('/getAllBooks', passport.authenticate('jwt', { session: false }), async function (req, res, next) {
    let client = await MongoClient.connect(config.url)      //获取数据库连接对象
    let db = client.db()
    let products = await db.collection('books').find({}).toArray()    //获取所有商品数据
    console.log('products:', products)
    if (products.length > 0) {
        res.json({ code: 200, message: 'ok', data: products });
    } else {
        res.json({ code: 200, message: 'error' });
    }
});


/*添加图书 */
router.post('/addBooks', passport.authenticate('jwt', { session: false }), async function (req, res, next) {
    //获取需要添加的订单商品信息
    let book = req.body.book
    console.log('book: ', book);
    //获取数据库连接对象
    let client = await MongoClient.connect(config.url)
    let db = client.db()
    // //执行添加订单的操作
    let results = await db.collection('books').insertOne(book)
    //判断是否添加成功
    if (results.acknowledged) {
        // let orders = await db.collection('books').find({ userId: req.user._id }).sort({ 'addTime': -1 }).toArray()
        res.json({
            code: 200, message: 'ok'
        });
    } else {
        res.json({ code: 200, message: 'error' });
    }
});



/*删除*/
router.delete('/delBooks', passport.authenticate('jwt', { session: false }), async function (req, res, next) {
    // 获取需要删除的id
    let id = req.query.id
    console.log('id =', id)
    //获取数据库连接对象
    let client = await MongoClient.connect(config.url)
    let db = client.db()
    //执行删除的操作
    let results = await db.collection('books').deleteOne({ _id: new mongdb.ObjectId(id) })
    console.log('results:', results)
    //判断是否删除成功
    if (results.acknowledged) {
        res.json({
            code: 200, message: 'ok'
        });
    } else {
        res.json({
            code: 200, message: 'error'
        });
    }
});

/* 修改图书 */
router.post('/updBooks', passport.authenticate('jwt', { session: false }), async function (req, res, next) {
    //获取需要添加的订单商品信息
    let updBook = req.body.updateBook
    console.log('updBook: ', updBook);
    //获取数据库连接对象
    let client = await MongoClient.connect(config.url)
    let db = client.db()
    let id = updBook._id
    // 删除原有数据
    let result1 = await db.collection('books').deleteOne({ _id: new mongdb.ObjectId(id) })
    // 新增数据
    let result2 = await db.collection('books').insertOne(updBook)
    // //判断是否添加成功
    if (result2.acknowledged && result1.acknowledged) {
        res.json({
            code: 200, message: 'ok'
        });
    } else {
        res.json({ code: 200, message: 'error' });
    }
});

module.exports = router;